package com.tony.demo.ui.home;


import android.content.Context;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.puhui.lib.utils.FormatUtil;
import com.tony.demo.R;
import com.tony.demo.bean.AdvertisementInfo;
import com.tony.demo.utils.glide.GlideUtils;

import java.util.ArrayList;
import java.util.List;


public class BannerAdapter extends PagerAdapter {
    // 界面列表
    private List<AdvertisementInfo> infos = new ArrayList<>(3);
    private Context mContext;

    public BannerAdapter(List<AdvertisementInfo> banners, Context context) {
        mContext = context;
        this.infos.clear();
        this.infos.addAll(banners);
    }

    /**
     * 获得当前界面数
     */
    @Override
    public int getCount() {
        return infos.size() > 0 ? Integer.MAX_VALUE : 1;
    }

    /**
     * 初始化position位置的界面
     */
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        final ImageView imageView = new ImageView(mContext);
        if (infos.size() > 0) {
            int currentInt = position % infos.size();
            AdvertisementInfo info = infos.get(currentInt);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            container.addView(imageView);
            imageView.setTag(R.id.glide_image_index, currentInt);

            GlideUtils.loadImage(mContext, info.getImgUrl(), imageView);

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int index = (Integer) v.getTag(R.id.glide_image_index);
                    AdvertisementInfo info = infos.get(index);
                    if (info != null && info.getLinkUrl() != null && FormatUtil.validateUrl(info.getLinkUrl())) {
                        //如果没有设置关联URL，则不进行任何操作  如果URL不正确，同样不做处理
//                        Intent intent = new Intent(mContext, WebViewActivity.class);
//                        intent.putExtra("linkUrl", info.getLinkUrl());
//                        intent.putExtra("title", info.getTitle());
//                        mContext.startActivity(intent);
                    }
                }
            });
        } else {
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setImageResource(R.mipmap.banner);
            container.addView(imageView);
        }
        return imageView;
    }

    /**
     * 判断是否由对象生成界面
     */
    @Override
    public boolean isViewFromObject(View view, Object arg1) {
        return view == arg1;
    }

    /**
     * 销毁position位置的界面
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
}